package cn.gcjxsc.controller.member;

import cn.gcjxsc.consts.CheckStatus;
import cn.gcjxsc.consts.ErrorConst;
import cn.gcjxsc.data.query.salesman.ApplyInfoQuery;
import cn.gcjxsc.data.vo.salesman.ApplyInfoVo;
import cn.gcjxsc.entity.member.Member;
import cn.gcjxsc.entity.merchant.Store;
import cn.gcjxsc.entity.salesman.ApplyInfo;
import cn.gcjxsc.entity.salesman.Salesman;
import cn.gcjxsc.exception.SQLException;
import cn.gcjxsc.form.ApplyInfoForm;
import cn.gcjxsc.service.config.SysConfigService;
import cn.gcjxsc.service.integral.ApplyInfoService;
import cn.gcjxsc.service.integral.SalesmanService;
import cn.gcjxsc.service.member.MemberService;
import cn.gcjxsc.service.merchant.StoreService;
import com.zgxl.common.util.AjaxResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务员操作类.
 *
 * @author pumbaa
 * @since 1.0
 */
@RestController
@RequestMapping("/api/member")
public class SalesmanController{
    @Autowired
    private SalesmanService salesmanService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ApplyInfoService applyInfoService;


    /**
     * 同意商户邀请操作
     *
     * @param storeId  店铺gid
     * @param memberId 会员id
     * @return
     */
    @RequestMapping("/salesman/agreeInvitation")
    public AjaxResponse agreeAction(@RequestParam("storeId") Integer storeId,
                                 @RequestParam("memberId") Integer memberId,
                                 @RequestParam(value = "nickname", defaultValue = "", required = false) String nickname) {
        /**
         * 1.基本信息是否存在
         * 2.会员绑定的业务员数量.
         * 3.会员与当前店铺的关系
         * 4.注册业务员.
         */
        if (null == storeId || null == memberId) {
            return AjaxResponse.ajaxFailure(ErrorConst.ILLEGAL_OPERATION);
        }
        Member member = memberService.findById(memberId);
        if (null == member) {
            return AjaxResponse.ajaxFailure(ErrorConst.MEMBER_NOT_FOUND);
        }
        Store store = storeService.findById(storeId);
        if (null == store || store.getCheckStatus() != CheckStatus.PASSED) {
            return AjaxResponse.ajaxFailure("无效店铺信息");
        }
        //查询是否申请过
        boolean hasApply = applyInfoService.isMemberAppling(member.getId(), storeId);
        if (hasApply) {
            return AjaxResponse.ajaxFailure("你已被邀请成为伙伴,请勿重复操作");
        }
        if (salesmanService.isStoreSalesman(memberId, storeId)) {
            return AjaxResponse.ajaxFailure("你已是该店铺的合作伙伴.");
        }

        long count = salesmanService.queryStoresForMember(member.getId());
        long max = sysConfigService.queryMaxStoreCountForMemberSalesman();
        if (max <= count) {
            return AjaxResponse.ajaxFailure("申请数已达上限");
        }
        member.setRealName(nickname);
        try {
            salesmanService.agreeInvitation(member, store);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResponse.ajaxSuccess();
    }

    /**
     * 是否存在申请中记录
     * @param storeId
     * @param memberId
     * @return
     */
    @RequestMapping("/salesman/hasApplyInfo")
    public boolean hasApplyInfo(@RequestParam("storeId") Integer storeId,
                                @RequestParam("memberId") Integer memberId){

        return applyInfoService.isMemberAppling(memberId, storeId);
    }

    /**
     * 申请成为店铺业务员
     *
     * @param form 会员id
     * @deprecated 从v1.1版本开始, 改用商户分享->用户同意方式成为业务员. 使用agreeAction()代替.
     */
    @RequestMapping("/salesman/apply")
    public AjaxResponse salesmanApply(@Valid ApplyInfoForm form, BindingResult bindingResult) {
        if (bindingResult.getErrorCount() > 0) {
            return AjaxResponse.ajaxFailure(bindingResult.getFieldError().getDefaultMessage());
        }
        Member member = memberService.findById(form.getMemberId());
        if (null == member) {
            return AjaxResponse.ajaxFailure(ErrorConst.MEMBER_NOT_FOUND);
        }
        Store store = storeService.findById(form.getStoreId());
        if (null == store || store.getCheckStatus() != CheckStatus.PASSED) {
            return AjaxResponse.ajaxFailure("无效店铺信息");
        }
        long count = salesmanService.queryStoresForMember(member.getId());
        long max = sysConfigService.queryMaxStoreCountForMemberSalesman();
        if (max <= count) {
            return AjaxResponse.ajaxFailure("申请数已达上限");
        }
        if (salesmanService.isStoreSalesman(form.getMemberId(), form.getStoreId())) {
            return AjaxResponse.ajaxFailure("你已通过该店铺申请,请勿重复申请");
        }
        try {
            salesmanService.applyForSalesman(form);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResponse.ajaxSuccess();
    }

    /**
     * 查询我的申请记录
     *
     * @param filter   过滤器
     * @param page     当前页
     * @param pageSize 每页记录数
     * @return
     */
    @RequestMapping("/query/myApplyInfoList")
    public AjaxResponse queryMyApplyInfoListAction(ApplyInfoQuery filter,
                                                @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
                                                @RequestParam(value = "pageSize", defaultValue = "30", required = false) Integer pageSize) {

        page = Math.abs(page);
        if (filter.getMemberId() == null) {
            return AjaxResponse.ajaxFailure("无效参数");
        }
        Page<ApplyInfo> info = applyInfoService.queryApplyInfo(filter, page, pageSize);
        List<ApplyInfo> applyInfos = info.getContent();
        long count = info.getTotalElements();
        List<ApplyInfoVo> voList = applyInfoService.converList(applyInfos);
        Map<String, Object> data = new HashMap<>();
        data.put("count", count);
        data.put("list", voList);
        return AjaxResponse.ajaxSuccess(data);

    }

    /**
     * 查询指定店铺的业务信息
     *
     * @param storeId  店铺id
     * @param memberId 会员id
     * @return
     */
    @RequestMapping("/query/storeSalesman")
    public Salesman findByStore(@RequestParam("storeId") Integer storeId,
                                @RequestParam("memberId") Integer memberId) {
        return salesmanService.findByStoreId(storeId, memberId);
    }
}
